<template>
  <div class="search-result-container">
    <!-- 点击实现后退效果 -->
    <van-nav-bar
      title="搜索结果"
      left-arrow
      @click-left="$router.go(-1)"
      fixed
    />
    <!-- 文章列表 -->
    <div>
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
       :immediate-check="false"
        offset="20"
      >
        <ArticleItem
          v-for="item in searchList"
          :key="item.art_id"
          :item="item"
          :boolean="false"
        ></ArticleItem>
      </van-list>
    </div>
  </div>
</template>

<script>
// 组件
import ArticleItem from '@/components/ArticleItem.vue'
// 接口
import { searchListAPI } from '@/api'
// 时间处理函数
import { toTimeAgo } from '@/utils/date'
export default {
  name: 'SearchResult',
  data () {
    return {
      page: 1, // 初始分页
      searchList: [], // 搜索结果列表
      loading: false, // 底部加载更多状态
      finished: false // 底部加载完成状态
    }
  },
  methods: {
    onLoad () {
      this.page++
      this.getSearchListFn()
    },
    async getSearchListFn () {
      const res = await searchListAPI({
        q: this.$route.params.keywords,
        page: this.page
      })
      if (res.data.data.results.length === 0) {
        this.finished = true
        return
      }
      res.data.data.results.forEach(obj => {
        // 时间处理
        obj.pubdate = toTimeAgo(obj.pubdate)
      })
      this.searchList = [...this.searchList, ...res.data.data.results]
      this.loading = false
    }
  },
  created () {
    this.getSearchListFn()
  },
  components: {
    ArticleItem
  }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>
